<?php

class DB {

	
    private static $instance = NULL;

    
    public function __construct() {

       global $CONFIG;

        if (!self::$instance) {

            $this->instance = new PDO("mysql:host=".$CONFIG->db_host.";dbname=".$CONFIG->db_name, $CONFIG->db_user, $CONFIG->db_pass);
            $this->instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        return $this->instance;
    }


    public function selectResponse($sql, $params=false) {

        $statement = $this->instance->prepare($sql);

        if ($params) {
            $statement->execute($params);
        } else {
            $statement->execute();
        }

        $result = $statement->fetch(PDO::FETCH_OBJ);

        return $result;
    }


    public function selectResponses($sql, $params=false) {

        $statement = $this->instance->prepare($sql);

        if ($params) {
            $statement->execute($params);
        } else {
            $statement->execute();
        }

        $result = array();
        while ($obj = $statement->fetch(PDO::FETCH_OBJ)) {

            $result[] = clone $obj;
        }

        return $result;
    }


    public function executeSql($sql, $params=false) {

        $statement = $this->instance->prepare($sql);

        if ($params) {
            $statement->execute($params);
        } else {
            $statement->execute();
        }

        return $this->instance->lastInsertId();
    }

    
    public function insertObject($tablename=false, $obj=false) {
    	
    	if (!$obj || !$tablename) {
    		return false;
    	}
    	
    	$fields = array();
    	$values = array();
    	$params = array();
    	foreach ($obj as $key => $value) {
    		
    		$fields[] = $key;
    		$values[] = '?';
    		$params[] = $value;
    	}
    	
    	$sql = "INSERT INTO ".$tablename." (".implode(', ', $fields).") VALUES (".implode(', ', $values).")";
    	
    	return $this->executeSql($sql, $params);
    }
    
    
    public function updateObject($tablename, $sets, $id=false) {
    	
    	if (!$sets || !$tablename) {
    		return false;
    	}
    	
    	$params = array();
    	$querysets = array();
    	foreach ($sets as $key => $value) {
    		$querysets[] = $key.' = ?';
    		$params[] = $value;
    	}

    	
    	$sql = "UPDATE ".$tablename." SET ".implode(', ', $querysets);

    	if ($id) {
    		$sql.= "WHERE id = ?";
    		$params[] = $id;
    	}
    	
    	$this->executeSql($sql, $params);
    }
    
}


?>
